﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace Infrastructure.Crosscutting.NetFramework.Validator
{
    public static class DataAnnotationsValidationRunner
    {
        public static IEnumerable<ValidationResult> GetErrors(object instance)
        {
            return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
                   from attribute in prop.Attributes.OfType<ValidationAttribute>()
                   where !attribute.IsValid(prop.GetValue(instance))
                   select new ValidationResult(attribute.ErrorMessage);
        }

        public static IEnumerable<ValidationResult> GetErrors<TEntity, TEntityMetaData>(object instance)
        {
            TypeDescriptor.AddProviderTransparent(
           new AssociatedMetadataTypeTypeDescriptionProvider(typeof(TEntity), typeof(TEntityMetaData)), typeof(TEntity));
            var res = new List<ValidationResult>();
            bool valid = System.ComponentModel.DataAnnotations.Validator.TryValidateObject(instance, new ValidationContext(instance, null, null), res, true);
            return res.AsEnumerable();
        }
    }

}
